/* eslint-disable no-param-reassign */
import axios from "axios";
// @ts-ignore
import { notification } from "antd";
// @ts-ignore
import { saveAs } from "file-saver";
// import { getToken } from "./auth";
import { storage } from "@/utils/Storage";
const token = storage.getCookie(import.meta.env.VITE_GLOB_TOKEN_KEY) || "";
import { blobValidate } from "./index";
// @ts-ignore
const baseURL: string = import.meta.env.VITE_GLOB_API_URL_PREFIX || "";
const clientId: string = import.meta.env.VITE_GLOB_CLIENT_ID || "";
const alertMessage = (msg: string) => {
	notification.error({
		message: "提示错误",
		description: msg
	});
};
export default {
	oss(ossId: number) {
		const url = `${baseURL}/resource/oss/download/${ossId}`;
		let key = "download_loading" + Math.random().toString(36).substring(2);
		notification.info({
			message: "下载消息",
			key: key,
			placement: "bottomRight",
			description: "正在下载数据，请稍候"
			// placement: 'bottomRight',
			// duration: 0,
			// icon: <SyncOutlined spin />,
		});

		axios({
			method: "get",
			url,
			responseType: "blob",
			headers: { Authorization: `Bearer ${token}`, clientid: clientId }
		})
			.then(res => {
				const isBlob = blobValidate(res.data);
				notification.destroy(key);
				if (isBlob) {
					const blob = new Blob([res.data], { type: "application/octet-stream" });
					this.saveAs(blob, decodeURI(res.headers["download-filename"]));
				} else {
					this.printErrMsg(res.data);
				}
			})
			.catch(r => {
				console.error(r);
				notification.destroy(key);
				alertMessage("下载文件出现错误，请联系管理员！");
			})
			.finally(() => {
				// downloadLoadingInstance.hide()
			});
	},
	export(url: string, param: any) {
		url = `${baseURL}${url}`;
		let exportKey = "export_loading" + Math.random().toString(36).substring(2);
		notification.info({
			message: "下载消息",
			key: exportKey,
			description: "正在下载数据，请稍候!"
			// placement: 'bottomRight',
			// duration: 0,
			// icon: <SyncOutlined spin />,
		});
		axios({
			method: "POST",
			url,
			data: param,
			responseType: "blob",
			headers: { Authorization: `Bearer ${token}`, clientid: clientId }
		})
			.then(res => {
				notification.destroy(exportKey);
				const isBlob = blobValidate(res.data);
				if (isBlob) {
					const blob = new Blob([res.data], { type: "application/octet-stream" });
					this.saveAs(blob, decodeURI(res.headers["download-filename"]));
				} else {
					this.printErrMsg(res.data);
				}
				return Promise.resolve();
			})
			.catch(r => {
				console.error(r);
				notification.destroy(exportKey);
				alertMessage("下载文件出现错误，请联系管理员！");
				return Promise.reject();
			})
			.finally(() => {
				return Promise.resolve();
				// downloadLoadingInstance.hide()
			});
	},
	zip(url: string, name: string) {
		// @ts-ignore
		url = baseURL + url;
		// const downloadLoadingInstance = LoadingPlugin({
		//   text: '正在下载数据，请稍候',
		//   attach: 'body',
		//   fullscreen: true,
		// });
		notification.open({
			message: "下载消息",
			description: "正在下载数据，请稍候",
			duration: 0
			// icon: <SyncOutlined spin />,
		});
		axios({
			method: "get",
			url,
			responseType: "blob",
			headers: {
				Authorization: `Bearer ${token}`,
				clientid: clientId,
				datasource: localStorage.getItem("dataName")
			}
		})
			.then(res => {
				const isBlob = blobValidate(res.data);
				if (isBlob) {
					const blob = new Blob([res.data], { type: "application/zip" });
					this.saveAs(blob, name);
				} else {
					this.printErrMsg(res.data);
				}
			})
			.catch(r => {
				console.error(r);
				alertMessage("下载文件出现错误，请联系管理员！");
			})
			.finally(() => {
				// downloadLoadingInstance.hide()
			});
	},
	saveAs(text: any, name: any, opts?: any) {
		saveAs(text, name, opts);
	},
	async printErrMsg(data: { text: () => any }) {
		const resText = await data.text();
		const rspObj = JSON.parse(resText);
		// @ts-ignore
		const errMsg = "系统出错了";
		// const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode.default;
		// await MessagePlugin.error(errMsg);
		alertMessage(errMsg);
	}
};
